#include "ht1621.h"
#include "gpio.h"
#include "time.h"
 

#define HT1621_CS_SET(index,x) do{\
			if((index) == 0)\
				GPIO_LCD_CS1(x);\
			else\
				GPIO_LCD_CS2(x);\
		}while(0)
 
void ht1621_send_high_order_data(uint8_t data, uint8_t len)
{
	uint8_t i;
 
	for (i=0; i<len; i++)
	{
		if((data&0x80) == 0)
		{
			GPIO_LCD_DATA(0);	
		}
		else
		{
			GPIO_LCD_DATA(1);
		}
		
		GPIO_LCD_WR(0);
		delayUs(4);
		GPIO_LCD_WR(1);	
		
		data <<= 1;
	}
}
 
void ht1621_send_low_order_data(uint8_t data, uint8_t len)
{
	uint8_t i;
	
	for (i=0; i<len; i++)
	{
		if((data&0x01) == 0)
		{
			GPIO_LCD_DATA(0);	
		}
		else
		{
			GPIO_LCD_DATA(1);
		}
		
		GPIO_LCD_WR(0);
		delayUs(4);
		GPIO_LCD_WR(1);	
		
		data >>= 1;
	}
}
 
void ht1621_send_cmd(uint8_t index, uint8_t command)
{
	HT1621_CS_SET(index,0);
	ht1621_send_high_order_data(0x80, 4);
	ht1621_send_high_order_data(command, 8);
	HT1621_CS_SET(index,1);	
}
 
void ht1621_write(uint8_t index, uint8_t addr, uint8_t data)
{
	HT1621_CS_SET(index,0);
	ht1621_send_high_order_data(0xA0, 3);
	ht1621_send_high_order_data(addr<<2, 6);
	ht1621_send_low_order_data(data, 8);
	HT1621_CS_SET(index,1);
}
 
void ht1621_write_all(uint8_t index, uint8_t addr, uint8_t *p, uint8_t len)
{
	uint8_t i;
	
	HT1621_CS_SET(index,0);
	ht1621_send_high_order_data(0xA0, 3);
	ht1621_send_high_order_data(addr<<2, 6);
	
	for (i=0; i<len; i++, p++)
	{
		ht1621_send_low_order_data(*p, 8);
	}
	
	HT1621_CS_SET(index,1);	
}
 
 
 
void ht1621_clr_all_display(uint8_t index)
{
	uint8_t i;
	uint8_t addr = 0;
	
	for (i=0; i<16; i++)
	{
		ht1621_write(index, addr, 0x00);
		addr += 2;
	}
}
 
void ht1621_all_display(uint8_t index)
{
	uint8_t i;
	uint8_t addr = 0;
	
	for (i=0; i<16; i++)
	{
		ht1621_write(index, addr, 0xFF);
		addr += 2;
	}	
}
 
void ht1621_init(void)
{
	ht1621_send_cmd(0, HT_SYS_EN);
	ht1621_send_cmd(0, HT_RCOSC);
	ht1621_send_cmd(0, HT_BISA_COM);
	ht1621_send_cmd(0, HT_LCD_ON);

	ht1621_send_cmd(1, HT_SYS_EN);
	ht1621_send_cmd(1, HT_RCOSC);
	ht1621_send_cmd(1, HT_BISA_COM);
	ht1621_send_cmd(1, HT_LCD_ON);
}
 
 
void set_lcd_on(uint8_t index)
{
	ht1621_send_cmd(index, HT_LCD_ON);
}
 
void set_lcd_off(uint8_t index)
{
	ht1621_send_cmd(index, HT_LCD_OFF);
}

